<script setup>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import {panelList, paperSize, getPaperSize, switchPanel} from "@/utils";
import {defaultElementTypeProvider} from '@/hiprint/hiprint.bundle.js'
import {yunProviderModule} from "@/utils/providers";
import {calculateTwoValue} from "@/utils";
import {initPanel} from "@/utils";
import {saveTemplate} from "@/api/template";
import {getUserInfo} from "@/utils/auth";
let saveTimeout = null;
let hiprintTemplate;

export default {
  props: ["templateData"],
  components: {
    CommonOperationForm
  },
  watch: {
    'list': {
      handler() {
        this.saveApi(hiprintTemplate.getJson()['panels'][0]);
      },
      deep: true,
    }
  },
  data() {
    return {
      aside_open_close: true,
      collapse: {
        activeNames: ['1', '2', '3', '4', '5', '6'],
        activeNames2: [],
        height: 'calc(100% - 48px)',
        toolList: [
          {
            name: '文本',
            iconName: 'text',
            tid: 'defaultModule.text',
          },
          {
            name: '图片',
            iconName: 'picture',
            tid: 'defaultModule.image',
          },
          {
            name: '横线',
            iconName: 'line',
            tid: 'defaultModule.hline',
          },
          {
            name: '竖线',
            iconName: 'y-line',
            tid: 'defaultModule.vline',
          },
          {
            name: '矩形',
            iconName: 'rect',
            tid: 'defaultModule.rect',
          }
        ],
        systemList: [
          {
            name: '单据编号',
            tid: 'yunProviderModule.documentNumber',
          },
          {
            name: '单据日期',
            tid: 'yunProviderModule.documentDate',
          },
          // {
          //   name: '单据时间',
          // },
          {
            name: '制单人',
            tid: 'yunProviderModule.employee',
          },
          {
            name: '结算账户',
            tid: 'yunProviderModule.settlementAccount',
          },
          {
            name: '结算账户备注',
            tid: 'yunProviderModule.accountRemarks',
          },
          {
            name: '打印时间',
            tid: 'yunProviderModule.printTime',
          },
          {
            name: '单据备注',
            tid: 'yunProviderModule.documentRemarks',
          },
          {
            name: '仓库',
            tid: 'yunProviderModule.warehouse',
          },
          {
            name: '@门店名称',
            tid: 'yunProviderModule.shopName',
          },
          {
            name: '@门店地址',
            tid: 'yunProviderModule.shopAddress',
          }
        ],
        amountList: [
          {
            name: '单据金额',
            tid: 'yunProviderModule.documentAmount',
          },
          {
            name: '折后金额',
            tid: 'yunProviderModule.discountedAmount',
          },
          {
            name: '其他费用',
            tid: 'yunProviderModule.otherAmount',
          },
          {
            name: '应付金额',
            tid: 'yunProviderModule.payableAmount',
          },
          {
            name: '合计实付',
            tid: 'yunProviderModule.totalAmount',
          },
          {
            name: '本单欠款',
            tid: 'yunProviderModule.dueAmount',
          },
          {
            name: '前期欠款',
            tid: 'yunProviderModule.frontAmount',
          },
          {
            name: '累计欠款',
            tid: 'yunProviderModule.totalDueAmount',
          },
          {
            name: '合计数量',
            tid: 'yunProviderModule.totalNumber',
          },
          {
            name: '定金',
            tid: 'yunProviderModule.deposit',
          },
        ],
        supplierList: [
          {
            name: '供应商名称',
            tid: 'yunProviderModule.contacts',
          },
          {
            name: '供应商编号',
            tid: 'yunProviderModule.supplierNumber',
          },
          {
            name: '供应商开户行',
            tid: 'yunProviderModule.supplierBank',
          },
          {
            name: '供应商银行账户',
            tid: 'yunProviderModule.supplierBankcard',
          },
          {
            name: '供应商税号',
            tid: 'yunProviderModule.supplierDutyParagraph',
          },
          // {
          //   name: '供应商社交账号',
          //   tid: 'yunProviderModule.suppl',
          // },
          {
            name: '供应商邮箱',
            tid: 'yunProviderModule.supplierEmail',
          },
          {
            name: '供应商备注',
            tid: 'yunProviderModule.supplierRemarks',
          },
          {
            name: '供应商分类',
            tid: 'yunProviderModule.supplierClassify',
          },
          {
            name: '供应商余额',
            tid: 'yunProviderModule.supplierBalance',
          },
        ],
        contactList: [
          {
            name: '联系人',
            tid: 'yunProviderModule.contacts',
          },
          {
            name: '联系电话',
            tid: 'yunProviderModule.telephone',
          },
          {
            name: '送货地址',
            tid: 'yunProviderModule.ship',
          },
        ],
        commonList: [
          {
            name: '单据抬头',
            tid: 'yunProviderModule.documentHeader',
          },
          {
            name: '公司地址',
            tid: 'yunProviderModule.companyAddress',
          },
          {
            name: '多联说明',
            tid: 'yunProviderModule.explain',
          },
          {
            name: '主营：',
            tid: 'yunProviderModule.mainProducts',
          },
        ],
        panelElList: [],
        chooseIndex: 0,
      },
      curPaper: {
        type: 'other',
        width: 220,
        height: 80
      },
      list: [
        {
          type: 'input',
          clearable: false,
          text: '模板名称：',
          size: 'mini',
          value: '',
        },
        {
          text: '纸张：',
          selectWidth: '150px',
          width: '40px',
          required: false,
          field: 'paperSize',
          size: 'mini',
          type: 'selectGroup',
          allowCreate: false,
          popperClass: getPaperSize(this.templateData.templateTypeName).className,
          options: getPaperSize(this.templateData.templateTypeName).options,
          value: '',
          changeEvent: (v) => {
            console.log("249", v, this.templateData['paper']);
            let template = switchPanel(this.templateData.templateTypeName, v.label);
            console.log("template: ", template);
            this.setPaper(v.label, v.attr);
            // 切换模版
            this.$emit('printDialogStatus', false, true, template, v);
            this.buildDesigner();
            // this.list[2].value = [v.attr.width, v.attr.height];
          }
        },
      ],
      scaleValue: 1,
      list2: [
        {
          field: 'paperSize',
          type: 'numberRangeSelect',
          value: {value: '100', label: '100%',},
          options: [
            {
              value: '50',
              label: '50%',
            },
            {
              value: '100',
              label: '100%',
            },
            {
              value: '200',
              label: '200%',
            },
            {
              value: '300',
              label: '300%',
            },
            {
              value: '400',
              label: '400%',
            }
          ],
          selectWidth: '80px',
          changeEvent: (v) => {
            v = v.value;
            v = v / 100;
            this.changeScale(v);
          }
        },
        {
          field: 'paperSize',
          type: 'numberRangeInput',
          value: '100%',
          borderLeft: '1px solid #DEE0E3',
          changeEvent: (v) => {
            console.log(v);
            let big = v;
            let scaleValue = this.scaleValue;
            if (big) {
              scaleValue += 0.1;
              if (scaleValue > 5) {
                scaleValue = 5;
                this.$message.error("操作提示：缩放比例，最大可以放大到500%");
              }
            } else {
              scaleValue -= 0.1;
              if (scaleValue < 0.5) {
                scaleValue = 0.5;
                this.$message.error("操作提示：缩放比例，最小可以缩小到50%");
              }
            }
            this.list2[0].value = calculateTwoValue(scaleValue, 100, 'mul', 0) + '%';
            console.log(this.list2[0].value)
            this.changeScale(scaleValue);
          }
        },
        {
          field: 'paperSize',
          type: 'numberRangeUndoRedo',
          value: '100%',
          borderLeft: '1px solid #DEE0E3',
          clickEvent: (v) => {
            console.log(v);
            if (v === 'undo') {
              hiprintTemplate.undo();
            } else if (v === 'redo') {
              hiprintTemplate.redo();
            }

            this.getAllEls();
            this.saveApi(hiprintTemplate.getJson()['panels'][0]);
          }
        },
        {
          field: 'paperSize',
          type: 'iconButton',
          loading: false,
          iconClass: 'bold',
          value: false,
          marginLeft: '10px',
          marginRight: '0px',
          borderLeft: '1px solid #DEE0E3',
          clickEvent: (v) => {
            this.list2[3].value = !this.list2[3].value;
            if (this.list2[3].value) {
              hiprintTemplate.updateOption('fontWeight', 'bolder');
            } else {
              hiprintTemplate.updateOption('fontWeight', '400');
            }
          }
        },
        {
          field: 'paperSize',
          marginLeft: '-10px',
          marginRight: '0px',
          type: 'iconButton',
          loading: false,
          iconClass: 'underline',
          value: false,
          borderLeft: 'none',
          clickEvent: (v) => {
            this.list2[4].value = !this.list2[4].value;
            if (this.list2[4].value) {
              hiprintTemplate.updateOption('textDecoration', 'underline');
            } else {
              hiprintTemplate.updateOption('textDecoration', '');
            }
          }
        },
        {
          field: 'paperSize',
          marginLeft: '-10px',
          marginRight: '0px',
          type: 'iconButton',
          loading: false,
          iconClass: 'left-side-align',
          value: false,
          borderLeft: 'none',
          clickEvent: (v) => {
            this.setElsAlign('left');
          }
        },
        {
          field: 'paperSize',
          marginLeft: '-10px',
          marginRight: '0px',
          type: 'iconButton',
          loading: false,
          iconClass: 'both-side-align',
          value: false,
          borderLeft: 'none',
          clickEvent: (v) => {
            this.setElsAlign('center');
          }
        },
        {
          field: 'paperSize',
          marginLeft: '-10px',
          marginRight: '0px',
          type: 'iconButton',
          loading: false,
          iconClass: 'right-side-align',
          value: false,
          borderLeft: 'none',
          clickEvent: (v) => {
            this.setElsAlign('right');
          }
        },
        {
          field: 'paperSize',
          marginLeft: '-10px',
          marginRight: '0px',
          type: 'iconButton',
          loading: false,
          iconClass: 'top-align',
          value: false,
          borderLeft: 'none',
          clickEvent: (v) => {
            this.setElsVerticalAlign('top');
          }
        },
        {
          field: 'paperSize',
          marginLeft: '-10px',
          marginRight: '0px',
          type: 'iconButton',
          loading: false,
          iconClass: 'middle-align',
          value: false,
          borderLeft: 'none',
          clickEvent: (v) => {
            this.setElsVerticalAlign('horizontal');
          }
        },
        {
          field: 'paperSize',
          marginLeft: '-10px',
          marginRight: '0px',
          type: 'iconButton',
          loading: false,
          iconClass: 'bottom-align',
          value: false,
          borderLeft: 'none',
          clickEvent: (v) => {
            this.setElsVerticalAlign('bottom');
          }
        },
        {
          field: 'paperSize',
          marginRight: '0px',
          marginLeft: '-5px',
          type: 'colorPicker',
          value: '#000000',
          borderLeft: 'none',
          clickEvent: (v) => {
            this.list2[11].value = v;
            hiprintTemplate.updateOption('color', v);
          }
        },
        {
          field: 'paperSize',
          type: 'iconButton',
          iconClass: 'preview',
          value: false,
          loading: false,
          iconName: '预览',
          title: '预览',
          marginLeft: '10px',
          marginRight: '0px',
          borderLeft: '1px solid #DEE0E3',
          clickEvent: (v) => {
            this.list2[12].loading = true;
            this.$nextTick(() => {
              hiprintTemplate.toPdf({}, '测试导出pdf', {isDownload: false, type: 'pdfobjectnewwindow'}).then((res) => {
                console.log('type:', type);
                console.log(res);
              });
              this.list2[12].loading = false;
            })
          }
        },
        {
          field: 'paperSize',
          type: 'iconButton',
          loading: false,
          iconClass: 'save2',
          value: false,
          title: '保存',
          iconName: '保存',
          marginLeft: '-10px',
          marginRight: '0px',
          borderLeft: 'none',
          clickEvent: (v) => {
            if (this.list[0].value === '') {
              this.$message.error("请填写模板名称");
              return;
            }
            console.log(this.list[0].value);
          }
        },
      ],
      paperTypes: {
        'A3': {
          width: 420,
          height: 296.6
        },
        'A4': {
          width: 210,
          height: 296.6
        },
        'A5': {
          width: 210,
          height: 147.6
        },
        'B3': {
          width: 500,
          height: 352.6
        },
        'B4': {
          width: 250,
          height: 352.6
        },
        'B5': {
          width: 250,
          height: 175.6
        }
      },
      save: false,
    }
  },
  mounted() {
    this.buildDesigner();
    this.generatePurchaseOrderPrefix();
  },
  methods: {
    buildDesigner() {
      console.log(this.templateData['template'], 537);
      let purchaseIncomingPanelInit = initPanel(this.templateData['template']);
      hiprint.init({
        providers: [defaultElementTypeProvider(), new yunProviderModule()],
      });

      hiprint.setConfig({
        optionItems: [
          function () {
            function t() {
              this.name = "paperNumberFormat";
            }

            return t.prototype.createTarget = function () {
              return this.target = $(`<div class="hiprint-option-item hiprint-option-item-row">
        <div class="hiprint-option-item-label">
        页码格式
        </div>
        <div class="hiprint-option-item-field">
            <select class="auto-submit">
                <option value="第一页/共一页">
                    第一页/共一页
                </option>
              </select>
        </div>
    </div>`), this.target;
            }, t.prototype.getValue = function () {
              console.log(this.target.find("select").val(), 401)
              return this.target.find("select").val();
            }, t.prototype.setValue = function (t) {
              console.log(t)
              if (t) {
                this.target.find("select").val(t)
              }
            }, t.prototype.destroy = function () {
              this.target.remove();
            }, t;
          }(),
          function () {
            function t() {
              this.name = "paperNumberDisabled";
            }

            return t.prototype.createTarget = function () {
              return this.target = $(`<div class="hiprint-option-item hiprint-option-item-row">
        <div class="hiprint-option-item-label">
                显示页码
        </div>
        <div class="hiprint-option-item-field">
                <select class="auto-submit">
                        <option value="">
                                显示
                        </option>
                        <option value="true">
                                隐藏
                        </option>
                </select>
        </div>
</div>`), this.target;
            }, t.prototype.getValue = function () {
              if ("true" === this.target.find("select").val()) {
                return true;
              } else {
                return false;
              }
            }, t.prototype.setValue = function (t) {
              if ('' === t || null === t || t === false) {
                this.target.find("select").val('');
              } else {
                this.target.find("select").val('true');
              }
              // _this.simulateClick();
            }, t.prototype.destroy = function () {
              this.target.remove();
            }, t;
          }(),
        ],
        panel: {
          supportOptions: [
            {
              name: 'paperNumberDisabled',
              hidden: false
            },
            {
              name: 'paperNumberFormat',
              hidden: false
            },
            {
              name: 'panelPaperRule',
              hidden: true
            },
            {
              name: 'panelPageRule',
              hidden: true
            },
            {
              name: 'firstPaperFooter',
              hidden: true
            },
            {
              name: 'evenPaperFooter',
              hidden: true
            },
            {
              name: 'oddPaperFooter',
              hidden: true
            },
            {
              name: 'lastPaperFooter',
              hidden: true
            },
            {
              name: 'leftOffset',
              hidden: true
            },
            {
              name: 'topOffset',
              hidden: true
            },
            {
              name: 'fontFamily',
              hidden: true
            },
            {
              name: 'orient',
              hidden: true
            },
            {
              name: 'paperNumberContinue',
              hidden: true
            },
            {
              name: 'watermarkOptions',
              hidden: true
            },
            {
              name: 'panelLayoutOptions',
              hidden: true
            },
          ],
          default: {}
        },
        text: {
          tabs: [
            {
              name: '基础', options: [
                {
                  name: 'title',
                  hidden: false
                },
                {
                  name: 'coordinate',
                  hidden: false
                },
                {
                  name: 'widthHeight',
                  hidden: false
                },
                {
                  name: 'hideTitle',
                  hidden: true
                },
                {
                  name: 'fixed',
                  hidden: true
                },
                {
                  name: 'field',
                  hidden: true
                },
                {
                  name: 'testData',
                  hidden: true
                },
              ]
            },
            {
              name: '样式', options: [
                {
                  name: 'dataType',
                  hidden: false
                },
                {
                  name: 'fontFamily',
                  hidden: false
                },
                {
                  name: 'fontSize',
                  hidden: false
                },
                {
                  name: 'fontWeight',
                  hidden: false
                },
                {
                  name: 'letterSpacing',
                  hidden: false
                },
                {
                  name: 'color',
                  hidden: false
                },
                {
                  name: 'backgroundColor',
                  hidden: false
                },
                {
                  name: 'textDecoration',
                  hidden: false
                },
                {
                  name: 'textAlign',
                  hidden: false
                },
                {
                  name: 'textContentVerticalAlign',
                  hidden: false
                },
                {
                  name: 'textContentWrap',
                  hidden: false
                },
                {
                  name: 'lineHeight',
                  hidden: false
                },
                {
                  name: 'transform',
                  hidden: false
                },
                {
                  name: 'zIndex',
                  hidden: false
                }
              ]
            },
            {
              name: '边框', options: [
                {
                  name: 'optionsGroup',
                  hidden: false
                },
                {
                  name: 'borderLeft',
                  hidden: false
                },
                {
                  name: 'borderTop',
                  hidden: false
                },
                {
                  name: 'borderRight',
                  hidden: false
                },
                {
                  name: 'borderBottom',
                  hidden: false
                },
                {
                  name: 'borderWidth',
                  hidden: false
                },
                {
                  name: 'borderColor',
                  hidden: false
                },
                {
                  name: 'contentPaddingLeft',
                  hidden: false
                },
                {
                  name: 'contentPaddingTop',
                  hidden: false
                },
                {
                  name: 'contentPaddingRight',
                  hidden: false
                },
                {
                  name: 'contentPaddingBottom',
                  hidden: false
                },
              ]
            },
          ],
          supportOptions: [
            {
              name: 'title',
              hidden: false
            },
            {
              name: 'field',
              hidden: false
            },
            {
              name: 'testData',
              hidden: false
            },
            {
              name: 'coordinate',
              hidden: false
            },
            {
              name: 'widthHeight',
              hidden: false
            },
            {
              name: 'dataType',
              hidden: false
            },
            {
              name: 'fontFamily',
              hidden: false
            },
            {
              name: 'fontSize',
              hidden: false
            },
            {
              name: 'fontWeight',
              hidden: false
            },
            {
              name: 'letterSpacing',
              hidden: false
            },
            {
              name: 'color',
              hidden: false
            },
            {
              name: 'textDecoration',
              hidden: false
            },
            {
              name: 'textAlign',
              hidden: false
            },
            {
              name: 'textContentVerticalAlign',
              hidden: false
            },
            {
              name: 'textContentWrap',
              hidden: false
            },
            {
              name: 'lineHeight',
              hidden: false
            },
            {
              name: 'textType',
              hidden: false
            },
            {
              name: 'barcodeMode',
              hidden: false
            },
            {
              name: "qrCodeLevel",
              hidden: false
            },
            {
              name: 'hideTitle',
              hidden: false
            },
            {
              name: 'pageBreak',
              hidden: false
            },
            {
              name: 'showInPage',
              hidden: false
            },
            {
              name: 'unShowInPage',
              hidden: false
            },
            {
              name: 'fixed',
              hidden: false
            },
            {
              name: 'axis',
              hidden: false
            },
            {
              name: 'transform',
              hidden: false
            },
            {
              name: 'zIndex',
              hidden: false
            },
            {
              name: 'optionsGroup',
              hidden: false
            },
            {
              name: 'borderLeft',
              hidden: false
            },
            {
              name: 'borderTop',
              hidden: false
            },
            {
              name: 'borderRight',
              hidden: false
            },
            {
              name: 'borderBottom',
              hidden: false
            },
            {
              name: 'borderWidth',
              hidden: false
            },
            {
              name: 'borderColor',
              hidden: false
            },
            {
              name: 'contentPaddingLeft',
              hidden: false
            },
            {
              name: 'contentPaddingTop',
              hidden: false
            },
            {
              name: 'contentPaddingRight',
              hidden: false
            },
            {
              name: 'contentPaddingBottom',
              hidden: false
            },
            {
              name: 'backgroundColor',
              hidden: false
            },
            {
              name: 'formatter',
              hidden: false
            },
            {
              name: 'styler',
              hidden: false
            }
          ],
          default: {
            width: 120,
            height: 9.75,
          }
        },
      });
      hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
      $("#yun-printer").empty();

      hiprintTemplate = new hiprint.PrintTemplate({
        template: {
          "panels": [purchaseIncomingPanelInit]
        },
        fontList: [
          {title: '微软雅黑', value: 'Microsoft YaHei'},
          {title: '黑体', value: 'STHeitiSC-Light'},
          {title: '思源黑体', value: 'SourceHanSansCN-Normal'},
          {title: '王羲之书法体', value: '王羲之书法体'},
          {title: '宋体', value: 'SimSun'},
          {title: '华为楷体', value: 'STKaiti'},
          {title: 'cursive', value: 'cursive'},
        ],
        onDataChanged: (type, json) => {
          console.log("type: ", type, " json: ", json);
          this.getAllEls();
          this.saveApi(json.panels[0]);
        },
        settingContainer: "#PrintElementOptionSetting",
      });

      hiprintTemplate.design("#yun-printer");
      window.hiprintTemplate = hiprintTemplate;
      // this.list[2].value = [paperSize[0].options[0].attr.width, paperSize[0].options[0].attr.height];
      this.list[1].value = this.templateData['paper'];
      this.scaleValue = this.templateData['scale'] || 1;
      this.list2[0].value = calculateTwoValue(this.scaleValue, 100, 'mul', 0) + '%';
      this.changeScale(this.scaleValue, false);
      console.log("scaleValue: ", this.scaleValue);

      this.$nextTick(() => {
        this.getAllEls();
        this.simulateClick();
      });
      TablePrintElement.prototype.getData = () => {
        return [
          {
            "sortNum": "@序号",
            "productName": "@商品名称",
            "specification": "@规格型号",
            "unit": "@单位",
            "inventory": "@数量",
            "price": "@单价",
            "totalPrice": "@金额",
            "remarks": "@备注信息",
            "attr": "@属性",
            "warehouse": "@所属仓库",
            "stock": "@当前库存",
            "serial": "@商品串码",
            "nums_lg": "@辅助数量",
            "nums_sm": "@基础数量",
            "batch": "@商品批次",
            "product_time": "@生产日期",
            "quality_day": "@有效期",
            "expire_time": "@失效日期",
            "brand": "@商品品牌",
            "number": "@商品编号",
            "class": "@商品分类",
            "code": "@条形码",
            "stocktip": "@库存预警",
            "location": "@商品货位",
            "retail_name": "@零售名称",
            "retail": "@零售价格",
            "goods_data": "@商品备注"
          }, {
            "sortNum": "1",
            "productName": "测试商品",
            "specification": "1.03kg",
            "unit": "个",
            "inventory": "1",
            "price": "0",
            "totalPrice": "0",
            "remarks": "",
            "attr": "",
            "warehouse": "",
            "stock": "",
            "serial": "",
            "nums_lg": "",
            "nums_sm": "",
            "batch": "",
            "product_time": "",
            "quality_day": "",
            "expire_time": "",
            "brand": "",
            "number": "",
            "class": "",
            "code": "",
            "stocktip": "",
            "location": "",
            "retail_name": "",
            "retail": "",
            "goods_data": ""
          }]
      }
      hiprintTemplate.update({"panels": [purchaseIncomingPanelInit]})
    },
    saveApi(template) {
      console.log("save");
      if (!this.templateData['templateID']) {
        this.$message.error("缺少ID");
        return;
      }

      if (this.list[0].value === '') {
        // this.$message.error("请填写模板名称");
        this.generatePurchaseOrderPrefix();
      }


      const saveData = () => {
        saveTemplate({
          userID: getUserInfo().userID,
          template,
          scale: this.scaleValue,
          templateName: this.list[0].value,
          paper: this.list[1].value,
          _id: this.templateData['templateID'] || '',
        }).then(res => {
          console.log(res);
          this.save = false;
        }).catch(res => {
          this.save = false;
        });
      }
      this.save = true;
      console.log(1122)
      clearTimeout(saveTimeout);
      // 设置新的保存定时器，延迟 1000 毫秒（即 1 秒）
      saveTimeout = setTimeout(saveData, 1000);
    },
    generatePurchaseOrderPrefix() {
      if (this.templateData['templateName'] === '') {
        let prefix = this.templateData['templateTypeName'];
        let now = new Date();
        let yearString = now.getFullYear().toString().slice(-2);
        let dateString = yearString +
            (now.getMonth() + 1).toString().padStart(2, '0') +
            now.getDate().toString().padStart(2, '0');
        let timeString = now.getHours().toString().padStart(2, '0') +
            now.getMinutes().toString().padStart(2, '0') +
            now.getSeconds().toString().padStart(2, '0');
        this.list[0].value = prefix + '-' + dateString + '' + timeString;
      } else {
        this.list[0].value = this.templateData['templateName'];
      }
    },
    setElsAlign(v) {
      this.list2[5].value = false;
      this.list2[6].value = false;
      this.list2[7].value = false;
      if (v === 'left') {
        this.list2[5].value = true;
        hiprintTemplate.updateOption('textAlign', 'left');
      } else if (v === 'center') {
        this.list2[6].value = true;
        hiprintTemplate.updateOption('textAlign', 'center');
      } else if (v === 'right') {
        hiprintTemplate.updateOption('textAlign', 'right');
        this.list2[7].value = true;
      }
    },
    setElsVerticalAlign(v) {
      this.list2[8].value = false;
      this.list2[9].value = false;
      this.list2[10].value = false;
      if (v === 'top') {
        this.list2[8].value = true;
        hiprintTemplate.updateOption('textContentVerticalAlign', 'top');
      } else if (v === 'horizontal') {
        this.list2[9].value = true;
        hiprintTemplate.updateOption('textContentVerticalAlign', 'middle');
      } else if (v === 'bottom') {
        hiprintTemplate.updateOption('textContentVerticalAlign', 'bottom');
        this.list2[10].value = true;
      }
    },
    changeScale(scaleValue, save = true) {
      if (hiprintTemplate) {
        hiprintTemplate.zoom(scaleValue);
        this.scaleValue = scaleValue;
      }

      if (save) {
        this.saveApi(hiprintTemplate.getJson()['panels'][0]);
      }
    },
    getAllEls() {
      let els = hiprintTemplate.getPanel().printElements;
      this.collapse.panelElList = [];
      for (let i = 0; i < els.length; i++) {
        this.collapse.panelElList.push({
          id: els[i].id,
          title: els[i].printElementType.title,
          type: els[i].printElementType.type,
        });
      }
      console.log(this.collapse.panelElList);
    },
    setPaper(type, value) {
      try {
        if (Object.keys(this.paperTypes).includes(type)) {
          this.curPaper = {type: type, width: value.width, height: value.height}
          hiprintTemplate.setPaper(value.width, value.height)
        } else {
          this.curPaper = {type: 'other', width: value.width, height: value.height}
          hiprintTemplate.setPaper(value.width, value.height)
        }
      } catch (error) {
        console.log(error);
        this.$message.error(`操作失败: ${error}`)
      }
    },
    exit() {
      this.$emit('printDialogStatus', false);
    },
    handleChange(val) {
      console.log(val);
    },
    handleChange2(val) {
      console.log(val);
      if (val.length <= 0) {
        this.collapse.height = 'calc(100% - 48px)';
      } else {
        this.getAllEls();
        this.collapse.height = 'calc(100% - 260px)';
      }
      console.log(this.collapse.height)
    },
    panelClickEvent(item, index) {
      console.log(item);
      this.collapse.chooseIndex = index;
      let el = hiprintTemplate.editingPanel.getElementById(item.id).designTarget;
      console.log(el);
      this.simulateClick(el.get(0));
    },
    simulateClick(el = document.getElementsByClassName("hiprint-paperNumber")[0]) {

      const clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });

      el.dispatchEvent(clickEvent);
    },
    clickEl() {
      setTimeout(() => {
        const setTextDefault = () => {
          this.list2[5].value = false;
          this.list2[6].value = false;
          this.list2[7].value = false;
        }

        const setVerticalTextDefault = () => {
          this.list2[8].value = false;
          this.list2[9].value = false;
          this.list2[10].value = false;
        }

        console.log(1181)
        let el = hiprintTemplate.getSelectEls();
        console.log(el, el.length);
        if (el && el[el.length - 1]) {
          let {textAlign, fontWeight, textDecoration, textContentVerticalAlign } = el[el.length - 1].options;
          if (textAlign && textAlign === 'left') {
            setTextDefault();
            this.list2[5].value = true;
          } else if (textAlign && textAlign === 'center') {
            setTextDefault();
            this.list2[6].value = true;
          } else if (textAlign && textAlign === 'right') {
            setTextDefault();
            this.list2[7].value = true;
          }

          if (fontWeight && (fontWeight >= 500 || fontWeight === "bolder")) {
            this.list2[3].value = true;
          } else {
            this.list2[3].value = false;
          }

          if (textDecoration && textDecoration === 'underline') {
            this.list2[4].value = true;
          } else {
            this.list2[4].value = false;
          }

          setVerticalTextDefault();
          if (textContentVerticalAlign && textContentVerticalAlign === 'top') {
            this.list2[8].value = true;
          } else if (textAlign && textAlign === 'horizontal') {
            this.list2[9].value = true;
          } else if (textAlign && textAlign === 'bottom') {
            this.list2[10].value = true;
          }
        }
      }, 300)
    },
    asidechange() {
      this.aside_open_close = !this.aside_open_close;
    },
  },
}
</script>

<template>
  <div class="yun-print">
    <div
        style="height: 64px; width: 100%; border-bottom: 1px solid #dadce0; position: relative; display: flex; align-items: center; ">
      <div class="yun-print-exit" @click="exit"
           style="padding: 4px 10px 4px 10px; display: flex; margin-right: 12px; border-radius: 4px; align-items: center; margin-left: 12px; cursor: pointer; ">
        <i class="el-icon-close" style="font-size: 22px; color: rgb(31, 35, 41); margin-right: 6px;'"/>
        <span
            style="font-size: 16px; line-height: 24px; color: #1f2329; margin-left: 2px; padding-right: 4px;  ">退出</span>
      </div>
      <div style="border-left: 1px solid #DEE0E3; line-height: 30px; display: flex; ">
        <common-operation-form style="color: rgb(31, 35, 41);" :list="list" :margin-top="'0px'" :margin-left="'12px'"/>
        <span style="margin-left: 10px; font-weight: 500; color: red;" v-show="save">
          <i class="el-icon-loading"></i>
          正在保存修改内容
        </span>
        <span style="margin-left: 10px; font-weight: 500; color: darkgreen;" v-show="!save">
          <i class="el-icon-success"></i>
          修改内容已保存
        </span>

      </div>
    </div>
    <div style="height: 38px; border-bottom: 1px solid #dadce0; display: flex; align-items: center;">
      <common-operation-form style="color: rgb(31, 35, 41);" :list="list2" :margin-top="'0px'" :margin-left="'0px'"/>
    </div>
    <div style="display: flex; flex-wrap: wrap; height: calc(100% - 64px - 38px); width: 100%;  overflow: hidden;">
      <div :class="[aside_open_close ? 'aside_open_close' : 'aside_open_close2']" @click="asidechange">
        <i class="el-icon-arrow-left" v-if="aside_open_close"></i>
        <i class="el-icon-arrow-right" v-else></i>
      </div>
      <div v-show="aside_open_close" style="border-right: 1px solid #e5e5e5; height: 100%; ">
        <el-scrollbar :style="`min-width: 230px; height: ${collapse.height}; width: 200px; `">
          <el-collapse style="margin: 0 10px;" v-model="collapse.activeNames" @change="handleChange">
            <el-collapse-item title="工具" name="1">
              <el-button
                  :style="`${index  % 2 === 0 ? 'margin-right: 6px; ' : ''}; ${index !== 0 && index !== 1 ? ' margin-top: 10px;' : ''}; width: 100px;`"
                  v-for="(item, index) in collapse.toolList"
                  :tid="item.tid" class="ep-draggable-item"
                  plain>
                <div style="padding: 2px 8px 8px;">
                  <svg-icon :icon-class="item.iconName" style="font-size: 34px;"/>
                </div>
                {{ item.name }}
              </el-button>
            </el-collapse-item>
            <el-collapse-item title="系统" name="6">
              <el-button size="mini" :tid="item.tid" class="ep-draggable-item"
                         :style="`${index  % 2 === 0 ? 'margin-right: 6px; ' : ''}; ${index !== 0 && index !== 1 ? ' margin-top: 10px;' : ''}; width: 100px;`"
                         v-for="(item, index) in collapse.systemList" plain>
                {{ item.name }}
              </el-button>
            </el-collapse-item>
            <el-collapse-item title="金额数量" name="2">
              <el-button size="mini" :tid="item.tid" class="ep-draggable-item"
                         :style="`${index  % 2 === 0 ? 'margin-right: 6px; ' : ''}; ${index !== 0 && index !== 1 ? ' margin-top: 10px;' : ''}; width: 100px;`"
                         v-for="(item, index) in collapse.amountList" plain>
                {{ item.name }}
              </el-button>
            </el-collapse-item>
            <el-collapse-item title="供应商相关" name="3">
              <el-button size="mini" :tid="item.tid" class="ep-draggable-item"
                         :style="`${index  % 2 === 0 ? 'margin-right: 6px; ' : ''}; ${index !== 0 && index !== 1 ? ' margin-top: 10px;' : ''}; width: 100px;`"
                         v-for="(item, index) in collapse.supplierList" plain>
                {{ item.name }}
              </el-button>
            </el-collapse-item>
            <el-collapse-item title="联系信息" name="4">
              <el-button size="mini" :tid="item.tid" class="ep-draggable-item"
                         :style="`${index  % 2 === 0 ? 'margin-right: 6px; ' : ''}; ${index !== 0 && index !== 1 ? ' margin-top: 10px;' : ''}; width: 100px;`"
                         v-for="(item, index) in collapse.contactList" plain>
                {{ item.name }}
              </el-button>
            </el-collapse-item>
            <el-collapse-item title="常用" name="5">
              <el-button size="mini" :tid="item.tid" class="ep-draggable-item"
                         :style="`${index  % 2 === 0 ? 'margin-right: 6px; ' : ''}; ${index !== 0 && index !== 1 ? ' margin-top: 10px;' : ''}; width: 100px;`"
                         v-for="(item, index) in collapse.commonList" plain>
                {{ item.name }}
              </el-button>
            </el-collapse-item>
          </el-collapse>
        </el-scrollbar>
        <div style="  min-width: 230px;   width: 200px;" class="yun-el-collapse">
          <el-collapse v-model="collapse.activeNames2" @change="handleChange2">
            <el-collapse-item name="1">
              <span slot="title" style="color: #1890ff; ">元素</span>
              <div v-for="(item, index) in collapse.panelElList" @click="panelClickEvent(item, index)"
                   :class="['yun-panel-els', 'drag_item_box', index === collapse.chooseIndex ? 'yun-panel-els-choose' : '']"
                   style="height: 34px; line-height: 34px; cursor: pointer;">
                <svg-icon style="margin-left: 0px; " :icon-class="item.type"/>
                <span style="margin-left: 10px; color: #000; font-size: 12px;">{{ item.title }}</span>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
      <div style="flex: 1; display: flex; overflow: auto; height: 100%; background: #d8dbe3;">
        <div id="yun-printer" style=" margin: auto; " @mousedown="clickEl"></div>
      </div>
      <div id="PrintElementOptionSetting"  style="min-width: 300px; width: 300px; border-left: 1px solid #e5e5e5;"></div>
    </div>
  </div>
</template>

<style lang="scss">
.hiprint-printPaper.design {
  box-shadow: 2px 2px 8px rgba(0, 0, 0, .1803921568627451);
  border: none !important;
  background: #fff;
}

.hiprint_rul_wrapper {
  display: none;
}

.yun-print-exit:hover {
  background: #1F23291A;
}


.hiprint-printElement-table thead {
  background: none;
}

/* .uptClass 类添加在 el-collapse 上 */

.yun-print .collapse-transition {
  -webkit-transition: 0s height, 0s padding-top, 0s padding-bottom;
  transition: 0s height, 0s padding-top, 0s padding-bottom;
}

.yun-print .horizontal-collapse-transition {
  -webkit-transition: 0s width, 0s padding-left, 0s padding-right;
  transition: 0s width, 0s padding-left, 0s padding-right;
}

.print-confirm-class .el-button {
  margin-left: 10px !important;
}

.yun-print .horizontal-collapse-transition .el-submenu__title .el-submenu__icon-arrow {
  -webkit-transition: 0s;
  transition: 0s;
  opacity: 0;
}

.yun-print .el-collapse-item__content {
  padding-bottom: 15px !important;
}

.yun-print .el-scrollbar__wrap {
  overflow-x: hidden;
}


.auto-submit {
  height: 30px !important;
  font-weight: 500 !important;
}

.hiprint-option-item-label {
  font-weight: 450 !important;
}

#PrintElementOptionSetting {
  color: #000000;
}

.hiprint-printPaper-content:not(.editing):hover .resize-panel {
  background-color: transparent !important;

}

.hiprint-printElement.design:hover .del-btn {
  //display: none;
}

.hiprint-option-item-field {
  margin-top: 6px;
}

.resize-panel .size-box {
  background: none !important;
}

.size-box {
  display: none !important;
}

.selected {
  background: none !important;
}


.yun-print {
  height: 100%;
}

.yun-print .el-button {
  margin-left: 0 !important;
}

.yun-el-collapse .el-collapse-item__header {
  //color: rgb(26 0 255);
}

.yun-el-collapse .el-icon-arrow-right:before {
  font-weight: 600;
  content: "展开";
}

.yun-el-collapse .is-active .el-icon-arrow-right:before {
  font-weight: 600;
  content: "";
}


.yun-el-collapse .el-collapse-item {
  padding: 0 10px;
}

.yun-el-collapse .el-collapse-item__wrap {
  border-top: 1px solid #e5e5e5;
  border-bottom: none !important;
}

.yun-print .el-button {
  color: #000;
}

.hiprint-footerLine:before {
  content: "页脚：点我可上下拖动页脚线";
  padding: 0 5px;
  position: absolute;
  height: 16.5pt;
  line-height: 16.5pt;
  right: 0;
  top: 0;
  border-bottom: none !important;
  border-right: none !important;
  cursor: move;
}

.hiprint-footerLine:before, .hiprint-headerLine:before {
  background: #f3f6fd;
  color: #a3a3a3;
  font-size: 12px;
  border: 1px dashed #c9c9c9 !important;
}

.hiprint-headerLine {
  border: none !important;
}

.design .hiprint-printElement-text-content {
  border: none;
}

.hiprint-footerLine {
  height: 17pt !important;
  border-top: 0 !important;
  border-bottom: 1px dashed #c9c9c9 !important;
}

.hiprint-option-item-settingBtn {
  display: none;
}

.design .resize-panel, .design .resize-panel:hover {
  border: 1px solid #1890ff !important;
}

.design .hiprint-printElement-table-content {
  background: #e7faf0;
}

.design .hiprint-printElement-table-handle {
  display: none;
}

.yun-print textarea {
  height: 166px !important;
}

.yun-print .hiprint-printPanel {
  padding: 50px;
}
</style>

<style scoped>
.aside_open_close {
  position: absolute;
  left: 230px;
  top: 90%;
  width: 12px;
  height: 40px;
  line-height: 40px;
  color: #fff;
  background-color: #1890ff;
  border-radius: 0 6px 6px 0;
  font-size: 12px;
  z-index: 1000;
  cursor: pointer;
}

.aside_open_close2 {
  position: absolute;
  left: 0px;
  top: 90%;
  width: 12px;
  height: 40px;
  line-height: 40px;
  color: #fff;
  background-color: #1890ff;
  border-radius: 0 6px 6px 0;
  font-size: 12px;
  z-index: 1000;
  cursor: pointer;
}

.aside_open_close:hover {
  background-color: #2A333A;
  color: #fff;
}

.yun-panel-els:hover {
  background-color: #f2f3f5 !important;
  border-color: #d0d3d6 !important;
}

.yun-panel-els-choose {
  background-color: #f2f3f5 !important;
  border-color: #d0d3d6 !important;
}


</style>
